package xyz.itpath.gen.util;

import org.springframework.beans.BeansException;
import org.springframework.boot.SpringApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring5.SpringTemplateEngine;
import org.thymeleaf.spring5.dialect.SpringStandardDialect;
import org.thymeleaf.templatemode.TemplateMode;
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * @author zhaom
 * @date 2021/9/23 - 11:14
 */
public class ThymeleafUtils {
    private final static SimpleDateFormat SDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    private static SpringTemplateEngine springTemplateEngine;

    private static void init() {
        if (springTemplateEngine == null) {
            SpringTemplateEngine springTemplateEngine = new SpringTemplateEngine();

            SpringStandardDialect springStandardDialect = new SpringStandardDialect();
            springTemplateEngine.setDialect(springStandardDialect);

            ClassLoaderTemplateResolver classLoaderTemplateResolver = new ClassLoaderTemplateResolver(ThymeleafUtils.class.getClassLoader());
            classLoaderTemplateResolver.setPrefix("templates/");
            classLoaderTemplateResolver.setSuffix(".java");
            classLoaderTemplateResolver.setCacheable(true);
            classLoaderTemplateResolver.setTemplateMode(TemplateMode.TEXT);

            springTemplateEngine.setTemplateResolver(classLoaderTemplateResolver);
            ThymeleafUtils.springTemplateEngine = springTemplateEngine;
        }
    }


    public static String genCode(String template, Map<String, Object> param) {
        ThymeleafUtils.init();

        Context context = new Context();
        param.put("time", SDF.format(new Date()));
        param.forEach(context::setVariable);
        return springTemplateEngine.process(template, context);
    }
}
